package com.example.service;

import com.example.bean.Role;
import com.example.bean.User;
import com.example.dao.RoleDao;
import com.example.dao.UserDao;
import com.example.util.MessageCode;
import com.example.util.MyToken;
import com.example.util.Result;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.example.util.MyMd5.encryptBASE64;

/**
 * Created by lianlei on 2017/1/12.
 */
@Service
public class UserServiceImp implements UserService {
    private UserDao dao;
    private RoleDao roleDao;

    public UserServiceImp(UserDao dao, RoleDao roleDao) {
        this.dao = dao;
        this.roleDao = roleDao;
    }

    @Override
    public Result loginByUser(User user , HttpServletRequest request) throws Exception {
        Map<String , Object> map = new HashMap<> ();
        List<User> users = dao.findAllByUsername(user.getUsername ());
        if ( users.isEmpty () ){
            return Result.getNew ().setM ("用户不存在").setC (MessageCode.MESSAGE_NULL_DATA);
        }else{
            if ( users.size () > 1 ){
                return Result.getNew ().setM ("您的账号已有风险，请重新注册！！！").setC (MessageCode.MESSAGE_USERNAME_REPEAT);
            }else{
                String s = encryptBASE64 (user.getPassword ());
                if ( s.equals (users.get (0).getPassword ()) ){
                    MyToken token = new MyToken (encryptBASE64 (user.getPassword ()) + "~" + encryptBASE64 (users.get (0).getId ().toString ()) , user.getUsername ());
                    map.put ("user",users.get (0));
                    map.put ("token",token);
                    return Result.getNew ().setC (MessageCode.MESSAGE_DATA_SUCCESS).setD (map).setM ("登录成功");
                }else {
                    return Result.getNew ().setM ("密码错误！！！").setC (MessageCode.MESSAGE_PASSWORD_ERORR);

                }
            }
        }
    }

    @Override
    public Result registered(User user) {
        List<User> users = dao.findAllByUsername (user.getUsername ());
        if ( users.isEmpty () ){
            user.setPassword (encryptBASE64 (user.getPassword ()));
            dao.saveAndFlush (user);
            System.out.println (user);
            return Result.getNew ().setC (MessageCode.MESSAGE_DATA_SUCCESS).setM ("提交成功！！！");
        }else{
            return Result.getNew ().setC (MessageCode.MESSAGE_USERNAME_REPEAT).setM ("用户已存在");
        }
    }

    @Override
    public Result addRoles(Role role) {
        Role roles = roleDao.findOneByRolename(role.getRolename ());
        if ( roles == null ){
            roleDao.saveAndFlush (role);
            return Result.getNew ().setM ("添加成功").setC (MessageCode.MESSAGE_DATA_SUCCESS);
        }
        return Result.getNew ().setC (MessageCode.MESSAGE_USERNAME_REPEAT).setM ("角色已存在！！！！");
    }
}
